<template>
  <div>
    <Search @refresh="onRefresh" @search="onSearch" @deleteAll="deleteAppUserAll">
      <el-button type="primary" :loading="false" @click="dialogVisible = true">添加客服</el-button>
    </Search>

    <!-- ============================================================================ -->
    <!-- ============================================================================ -->
    <el-table :data="tableData" ref="qtable" border v-loading="loading">
      <el-table-column prop="mark" label="包号" align="center" />
      <el-table-column prop="contact" label="联系方式" align="center" />
      <el-table-column prop="devnum" label="绑定设备次数" align="center" />
      <!-- <el-table-column prop="totalcopy" label="总复制次数" align="center" /> -->
      <el-table-column prop="todaycopy" label="今日复制次数" align="center" />
      <!-- <el-table-column prop="totalnum" label="总跳转次数" align="center" /> -->
      <el-table-column prop="todaynum" label="跳转失败" align="center" />
      <el-table-column label="类型" align="center">
        <template #default="scope">{{ jobtype(scope.row.type) }}</template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template #default="scope">{{ time(scope.row.createTime) }}</template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="onChangeStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label align="center">
        <template #default="scope">
          <div class="button">
            <i class="el-icon-delete"></i>
            <el-button type="text" @click="onClickDeleteUser(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- ============================================================================ -->
    <!-- ============================================================================ -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="15"
        hide-on-single-page
        @current-change="onCurrentChange"
      ></el-pagination>
    </div>

    <!-- ============================================================================ -->
    <!-- ============================================================================ -->
    <el-dialog
      title="添加客服"
      v-model="dialogVisible"
      width="30%"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div class="radio-ma">
        <el-radio v-model="type" label="0">QQ</el-radio>
        <el-radio v-model="type" label="1">微信</el-radio>
        <el-radio v-model="type" label="2">微信公众号</el-radio>
        <el-radio v-model="type" label="5">客户系统模式</el-radio>
      </div>
      <el-input type="textarea" :rows="10" placeholder="请输入内容" v-model="textarea"></el-input>
      <!-- <el-input placeholder="请输入在线客户地址" v-model="textarea"  class="radioinput"></el-input> -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="onAddContact" size="small">添加账户</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang='ts'>
import { reactive, ref, toRefs } from "vue";
import { Get, Post } from "@/api";
import Search from "@/components/search/Search.vue";
import $routet from "@/router/index";
import { $message, time } from "@/components/element";
export default {
  name: " ",
  components: { Search },
  setup() {
    const data = reactive({
      tableData: [],
      total: 0,
      loading: false,
      dialogVisible: false,
      textarea: "",
      type: "0",
    });

    /* 添加 */
    type DContact = string[] | null
    const onAddContact = async () => {
      let contact: DContact
      if (data.type == "0") {
        const reg = new RegExp(/[0-9]{5,10}/g)
        contact = data.textarea.match(reg);
      } else {
        contact = data.textarea.split(/\s/);
      }
      let markid = $routet.currentRoute.value.query.mark;
      try {
        if (!data.textarea) return $message("error", "内容不能为空");
        const deleteResult = await Post({
          url: "addContact",
          data: {
            contact,
            type: parseInt(data.type),
            mark: markid,
          },
        });
        if (deleteResult.data.code == 200) {
          $message("success", deleteResult.data.message);
          data.dialogVisible = false;
          data.textarea = "";
          onRefresh();
        }
      } catch (error) {
        console.log(error);
        if (error.data) {
          $message("error", error.data.message);
        }
      }
    };

    /* 分页 */
    let pageNo: number = 1;
    const onCurrentChange = async (val: number) => {
      pageNo = val;
      await getContactList(val);
    };

    /* 查询列表 */
    const qtable = ref();
    const getContactList = async (pageNo = 1) => {
      let markid = $routet.currentRoute.value.query.mark;
      //  console.log(markid);

      try {
        data.loading = true;
        const userListResult = await Get({
          url: "getContactList",
          data: {
            pageNo,
            mark: markid,
            pageSize: 15,
          },
        });
        data.tableData = userListResult.data.data;
        data.total = userListResult.data.total;
        qtable.value.doLayout();
        data.loading = false;
      } catch (error) {
        console.log(error);
        if (error.data) {
          $message("error", error.data.message);
        }
      }
    };
    getContactList();

    /* 刷新 */
    const onRefresh = async () => {
      await getContactList(pageNo);
    };

    /* 搜索 */
    const onSearch = async (valeu: string) => {
      let markid = $routet.currentRoute.value.query.mark;
      try {
        data.loading = true;
        const userListResult = await Get({
          url: "searchContact",
          data: {
            mark: markid,
            name: valeu,
          },
        });
        data.tableData = userListResult.data.data;
        data.total = userListResult.data.total;
        qtable.value.doLayout();
        data.loading = false;
      } catch (error) {
        console.log(error);
        if (error.data) {
          $message("error", error.data.message);
        }
      }
    };

    /* 删除 */
    const onClickDeleteUser = async (param: { _id: string }) => {
      try {
        const deleteResult = await Post({
          url: "deleteContact",
          data: {
            id: param._id,
          },
        });
        if (deleteResult.data.code == 200) {
          $message("success", deleteResult.data.message);
          onRefresh();
        }
      } catch (error) {
        console.log(error);
        if (error.data) {
          $message("error", error.data.message);
        }
      }
    };

    /* 删除全部 */
    const deleteAppUserAll = async () => {
      try {
        const deleteResult = await Post({
          url: "deleteContactAll",
          data: {
            mark: $routet.currentRoute.value.query.mark,
          },
        });
        if (deleteResult.data.code == 200) {
          $message("success", deleteResult.data.message);
          onRefresh();
        }
      } catch (error) {
        console.log(error);
        if (error.data) {
          $message("error", error.data.message);
        }
      }
    };

    /*修改状态  */
    let timeout: any = null;
    const onChangeStatus = (param: { _id: string; status: boolean }) => {
      if (timeout) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(async () => {
        try {
          const updateResult = await Post({
            url: "updateContact",
            data: {
              id: param._id,
              status: param.status,
            },
          });
          if (updateResult.data.code == 200) {
            $message("success", updateResult.data.message);
          }
        } catch (error) {
          console.log(error);
          if (error.data) {
            $message("error", error.data.message);
          }
        }
      }, 200);
    };

    /* 返回对应类型 */
    const jobtype = (type: number) => {
      switch (type) {
        case 0:
          return "QQ";
        case 1:
          return "微信";
        case 2:
          return "公众号";
        case 5:
          return "客户系统";
        default:
          return "未知类型";
      }
    };

    return {
      ...toRefs(data),
      onClickDeleteUser,
      onCurrentChange,
      onChangeStatus,
      deleteAppUserAll,
      onRefresh,
      onSearch,
      qtable,
      time,
      onAddContact,
      jobtype,
    };
  },
};
</script>
<style lang="less" scoped>
.radioinput {
  width: 70%;
  margin: 10px auto;
  display: block;
}
.radio-ma {
  margin-bottom: 20px;
  text-align: center;
}
.button,
.el-button--text {
  color: red;
}
.button:hover,
.el-button--text:hover {
  color: red;
}
.pagination {
  margin-top: 20px;
  display: flex;
  position: relative;
  .el-pagination {
    position: absolute;
    right: 0;
  }
}
</style>